import React, { Component } from 'react'
import { connect } from 'react-redux'
import UrlPattern from 'url-pattern'
import { withRouter } from 'react-router-dom'
import { Col, Icon, Row, Tabs } from 'antd'
import { TwsBelongTask } from 'tws-antd'
import EditStatusBox from './assignment/edit-status-box'
import CommentBox from './assignment/comment-box'
import ReferenceButtonGroup from './assignment/reference-button-group'
import Homework from './assignment/homework-quiz'
import * as actions from '../actions/homework'
import * as userActions from '../actions/user'
import * as reviewActions from '../actions/reviewQuiz'
import * as sectionCommentActions from '../actions/comment'
import AssignmentSupplementaryBox from './assignment/assignment-supplementary-box'
import { addNotification } from '../actions/notification'
import '../less/index.less'
import { tutorAssignmentPageBodyUrl } from '../constant/constant-url'
import LeftMenu from './assignment/left-menu'
import { FormattedMessage } from 'react-intl'
import { getLangFromLocalStorage } from '../constant/lang-util'
import AssignmentTagBox from './assignment/assignment-tag-box'
import * as assignmentQuizTagAction from '../actions/assignment-quiz-tag'
import AssignmentEvaluateBox from './common/assignment-evaluate-box'
import AssignmentRankingBox from './common/assignment-ranking-box'
import * as assignmentQuizMarkAction from '../actions/assignment-quiz-Mark'
import {submitNote} from '../actions/notes'

const TabPane = Tabs.TabPane
class TutorAssignmentPageBody extends Component {
  constructor (props) {
    super(props)
    this.state = {
      programId: 0,
      taskId: 0,
      assignmentId: 0,
      studentId: 0,
      quizId: 0
    }
  }

  componentWillMount () {
    const {history, location} = this.props
    history.listen(this.update.bind(this))
    this.update(location)
    const {programId} = this.props.match.params
    this.props.getTutorFollowStudent(programId)
  }

  update (location) {
    const pattern = new UrlPattern(tutorAssignmentPageBodyUrl)
    const urlParams = pattern.match(location.pathname.replace('divider/', '')) || {}
    const {taskId, programId, assignmentId, studentId, quizId} = urlParams

    this.setState({
      taskId,
      programId,
      assignmentId,
      studentId,
      quizId
    })
    if (quizId) {
      this.props.getTask(taskId)
      this.props.getComments(assignmentId, studentId, quizId)
      this.props.getReviewQuiz(assignmentId, studentId, quizId)
      this.props.getStudent(studentId)
      this.props.getHomeworkQuizzesByStudentId(assignmentId, studentId)
      this.props.getStudentAssignmentQuizTags(assignmentId, quizId, studentId)
      this.props.getAssignmentQuizMark(assignmentId, quizId, studentId)
      this.props.getRunningLogs(taskId, assignmentId, quizId, 0)
    }
  }

  handleClick (e) {
    const {assignmentId, quizId, programId, taskId} = this.state
    this.props.history.push(`/tutor/program/${programId}/task/${taskId}/student/${parseInt(e.key, 10)}/assignment/${assignmentId}/quiz/${quizId}`)
    this.setState({studentId: parseInt(e.key, 10)})
  }
  getCompleteName (student) {
    const name = student.name || ''
    const userName = student.userName || ''

    return `${name}(@${userName})`
  }

  render () {
    const {suggestions, quizzes, review, task, student, settings, students, assignmentQuizMark, runningLogs, user} = this.props
    const {taskId, programId, assignmentId, studentId, quizId} = this.state
    const { tutorWebUrl } = settings
    const assignment = task.assignments.find(assignment => assignment.id === parseInt(assignmentId, 10)) || {}
    const quiz = quizzes.find(quiz => parseInt(quizId) === quiz.id) || {}
    const completeName = this.getCompleteName(student)
    const type = 'tutor'
    const lang = getLangFromLocalStorage()

    return <div>
      <Row className='margin-t-2'>
        <Col span={3}>
          <LeftMenu students={students} studentId={studentId} handleClick={this.handleClick.bind(this)} />
        </Col>
        <Col offset={1} span={20}>
          <div>
            <Row >
              <Col span={8}>
                <h2>{assignment[`title_${lang}`] || assignment.title}</h2>
              </Col>
              <Col span={2}>
                {
                  programId
                    ? <ReferenceButtonGroup
                      isTutor
                      review={review}
                      programId={programId}
                      quizId={quiz.id}
                      taskId={taskId}
                      assignmentId={assignmentId}
                      quizDefinition={quiz}
                      studentId={studentId} />
                    : ''
                }
              </Col>
              <Col span={6} offset={6}>
                <EditStatusBox
                  isTutor
                  review={review}
                  assignmentId={assignmentId}
                  quizId={quiz.id}
                  taskId={taskId}
                  studentId={studentId}
                  isSubmit={quiz.userAnswer !== ''}
                  programId={this.state.programId}
                  addNotification={this.props.addNotification}
                  updateReviewGrade={this.props.updateReviewGrade}
                />
              </Col>
            </Row>
            <Row >
              <Col>
                <div><Icon type='user' /> {completeName}</div>
              </Col>
            </Row>
          </div>
          <TwsBelongTask title={<FormattedMessage id='所属任务卡' />}>
            <a
              href={tutorWebUrl + `/program/${this.state.programId}/task/${this.state.taskId}/student/${this.state.studentId}`}>
              <Icon type='arrow-left' />{task[`title_${lang}`] || task.title}
            </a>
            <AssignmentTagBox
              programId={programId}
              assignmentId={assignmentId}
              quizId={quizId}
              studentId={studentId}
            />
          </TwsBelongTask>
          {
            quiz.id
              ? <Homework
                isTutor
                runningLogs={runningLogs}
                programId={this.state.programId}
                taskId={this.state.taskId}
                assignmentId={this.state.assignmentId}
                reviewQuiz={review}
                quiz={quiz}
                user={user}
                submitNote={this.props.submitNote}
            />
              : ''
          }
          <AssignmentSupplementaryBox
            reviewQuiz={review}
            userType={type}
          />
          <AssignmentRankingBox
            programId={programId}
            assignmentId={assignmentId}
            quizId={quizId}
            studentId={studentId}
            assignmentQuizMark={assignmentQuizMark}
          /><br />
          <Tabs defaultActiveKey='1' type='card' >
            <TabPane tab={<h4><FormattedMessage id='助教反馈' /></h4>} key='1'>
              <CommentBox
                suggestions={suggestions}
                isTutor
                user={this.props.user}
                programId={this.state.programId}
                taskId={this.state.taskId}
                assignmentId={assignmentId}
                studentId={studentId}
                quizId={quiz.id}
              />
            </TabPane>
            <TabPane tab={<h4><FormattedMessage id='隐藏评价' /></h4>} key='2'>
              <AssignmentEvaluateBox
                programId={programId}
                assignmentId={assignmentId}
                quizId={quizId}
                studentId={studentId}
                assignmentQuizMark={assignmentQuizMark}
              />
            </TabPane>
          </Tabs>
        </Col>
      </Row>
    </div>
  }
}

const mapStateToProps = ({student, students, user, homeworkQuizzes, review, comments, task, settings, assignmentQuizMark, runningLogs}) => ({
  user,
  review,
  quizzes: homeworkQuizzes,
  quizAnswerSheet: {
    isFinished: true,
    isLast: true,
    isStarted: true,
    status: 4
  },
  task,
  suggestions: comments,
  settings,
  student,
  students,
  assignmentQuizMark,
  runningLogs
})

const mapDispatchToProps = dispatch => ({
  getHomeworkQuizzesByStudentId: (assignmentId, studentId) => dispatch(actions.getStudentHomeworkQuizzes(assignmentId, studentId)),
  getComments: (assignmentId, studentId, quizId) => dispatch(sectionCommentActions.getSectionComments(assignmentId, studentId, quizId)),
  getReviewQuiz: (assignmentId, studentId, quizId) => dispatch(reviewActions.tutorGetReviewHomeworkQuiz(assignmentId, studentId, quizId)),
  updateReviewGrade: (data, changeStatus) => dispatch(reviewActions.updateReviewQuiz(data, changeStatus)),
  getTask: (taskId) => dispatch(actions.getTask(taskId)),
  getStudent: (studentId) => dispatch(userActions.getStudent(studentId)),
  addNotification: (data) => dispatch(addNotification(data)),
  getTutorFollowStudent: (programId) => dispatch(actions.getTutorFollowStudent(programId)),
  getStudentAssignmentQuizTags: (assignmentId, quizId, studentId) => dispatch(assignmentQuizTagAction.getStudentAssignmentQuizTags(assignmentId, quizId, studentId)),
  getAssignmentQuizMark: (assignmentId, quizId, studentId) => dispatch(assignmentQuizMarkAction.getAssignmentQuizMark(assignmentId, quizId, studentId)),
  getRunningLogs: (taskId, assignmentId, quizId, submissionId, getResult) => dispatch(actions.getRunningLogs(taskId, assignmentId, quizId, submissionId, getResult)),
  submitNote: quizNote => dispatch(submitNote(quizNote))
})

export default withRouter(connect(mapStateToProps, mapDispatchToProps)(TutorAssignmentPageBody))
